﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;
using CarFileManager.Models;

namespace CarFileManager
{
    /// <summary>
    /// Describes the behaviour of a Car data storage implemented as an XML file.
    /// </summary>
    public sealed class XmlCarFile : CarFileBase
    {
        /// <summary>
        /// Initialises a new instance of the XmlCarFile.
        /// </summary>
        /// <param name="fileName">A full path to the XML file used as a Car data storage.</param>
        public XmlCarFile(string fileName) : base(fileName)
        {
        }

        /// <summary>
        /// Reads the FileName specified file and fills the Cars collection.
        /// </summary>
        protected internal override void ReadFile()
        {
            try
            {
                using (Stream stream = new FileStream(FileName, FileMode.Open))
                {
                    var reader = new XmlSerializer(typeof(XmlCarDocument));
                    var document = (XmlCarDocument)reader.Deserialize(stream);
                    Cars.AddRange(document.Cars);
                }
            }
            catch (Exception e)
            {

            }
        }

        protected internal override void SaveFile()
        {
            using (Stream stream = new FileStream(FileName, FileMode.Create))
            {
                try
                {
                    var writer = new XmlSerializer(typeof(XmlCarDocument));
                    var document = new XmlCarDocument(Cars);
                    writer.Serialize(stream, document.Cars);
                }
                catch (Exception e)
                {

                }
            }
        }

        /// <summary>
        /// A helper class, which is used to implement the XML serialisation of a collection.
        /// </summary>
        [XmlRoot("Document")]
        public class XmlCarDocument
        {
            public XmlCarDocument()
            {
                Cars = new List<XmlCar>();
            }

            public XmlCarDocument(List<ICar> cars)
            {
                Cars = cars.ConvertAll(car => new XmlCar { Date = car.Date, BrandName = car.BrandName, Price = car.Price });
            }
            
            [XmlElement("Car")]
            public List<XmlCar> Cars { get; set; }
        }
    }
}
